﻿/*
 * 
 * Copyright 2008 Digital Cinema Implementation Partners (DCIP)
 * See the NOTICE file distributed with this work for additional information regarding copyright ownership.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.  You may obtain a copy of the License at
 * 
 *                 http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing permissions and limitations
 * under the License.
 * 
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using System.ServiceModel.Configuration;
using System.Configuration;
using dcipllc.com._2009._07.SiteList;


namespace FLMTestUserInterface
{
    public partial class FLMTestForm : Form
    {
        public FLMTestForm()
        {
            InitializeComponent();

            richTextBox_Request.SetBounds(0, 0, tabRequest.Width, tabRequest.Height);
            richTextBox_Reply.SetBounds(0, 0, tabReply.Width, tabReply.Height);

            ClientSection clientSection = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection; 
            ChannelEndpointElementCollection endpointCollection = clientSection.ElementInformation.Properties[string.Empty].Value as ChannelEndpointElementCollection; 
            foreach (ChannelEndpointElement endpointElement in endpointCollection) 
            { 
                comboBox_location.Items.Add(endpointElement.Name);
            }

            foreach (string key in ConfigurationManager.AppSettings.AllKeys)
            {
                identifier_uri.Items.Add(key);
            }

            if(identifier_uri.Items.Count > 0)
                identifier_uri.SelectedIndex = 0;

            if(comboBox_location.Items.Count > 0)
                comboBox_location.SelectedIndex = 0;

        }

        private void get_facility_list_Click(object sender, EventArgs e)
        {
            FlmServiceClient client = null;
            try
            {
                client = new FlmServiceClient(comboBox_location.Text);
            }
            catch (Exception eFLM)
            {
                richTextBox_Reply.Text = eFLM.Message;

                try
                {
                    client.Close();
                }
                catch (Exception eService)
                {
                    richTextBox_Reply.Text += "\n\nThe FLM Service closed with the following error:\n   " + eService.Message;
                }

                return;
            }

            client.ClientCredentials.UserName.UserName = username.Text;
            client.ClientCredentials.UserName.Password = password.Text;

            string request = "urn:x-facilityID:" + identifier_uri.Text + ":" + identifier.Text;
            richTextBox_Request.Text = "GetFLM(" + request + ")";

            Cursor lastCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            DateTime startTime = DateTime.Now;
            DateTime endTime = startTime;
            TimeSpan duration = endTime - startTime;

            ResponseTime.Clear();
            SitesReturned.Clear();
            richTextBox_Reply.Clear();

            System.Xml.XmlElement reply = null;
            try
            {
                reply = client.GetFLM(request);

                endTime = DateTime.Now;
                duration = endTime - startTime;
                ResponseTime.Text = duration.TotalSeconds.ToString();

                SitesReturned.Text = "1";
            }
            catch (Exception eFLM)
            {

                endTime = DateTime.Now;
                duration = endTime - startTime;
                ResponseTime.Text = duration.TotalSeconds.ToString();

                SitesReturned.Text = "0";

                Cursor.Current = lastCursor;

                richTextBox_Reply.Text = eFLM.Message;

                try
                {
                    client.Close();
                }
                catch (Exception eService)
                {
                    richTextBox_Reply.Text += "\n\nThe FLM Service closed with the following error:\n   " + eService.Message;
                }

                return;
            }

            Cursor.Current = lastCursor;

            richTextBox_Reply.Text = reply.OuterXml;

            try
            {
                client.Close();
            }
            catch (Exception eService)
            {
                richTextBox_Reply.Text += "\n\nThe FLM Service closed with the following error:\n   " + eService.Message;
            }
        }

        private void query_sites_Uri()
        {
            FlmServiceClient client = null;
            try
            {
                client = new FlmServiceClient(comboBox_location.Text);
            }
            catch (Exception eFLM)
            {
                richTextBox_Reply.Text = eFLM.Message;

                try
                {
                    client.Close();
                }
                catch (Exception eService)
                {
                    richTextBox_Reply.Text += "\n\nThe FLM Service closed with the following error:\n   " + eService.Message;
                }

                return;
            }

            client.ClientCredentials.UserName.UserName = username.Text;
            client.ClientCredentials.UserName.Password = password.Text;

            string request = "since:" + dateTimePicker_ChangedSince.Value.ToShortDateString();
            richTextBox_Request.Text = "GetUpdatedFacilityListSince(" + request + ")";

            Cursor lastCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            DateTime startTime = DateTime.Now;
            DateTime endTime = startTime;
            TimeSpan duration = endTime - startTime;

            ResponseTime.Clear();
            SitesReturned.Clear();
            richTextBox_Reply.Clear();

            SiteListType reply = null;
            try
            {
                reply = client.GetUpdatedFacilityListSince(request);

                endTime = DateTime.Now;
                duration = endTime - startTime;
                ResponseTime.Text = duration.TotalSeconds.ToString();
            }
            catch (Exception eFLM)
            {
                endTime = DateTime.Now;
                duration = endTime - startTime;
                ResponseTime.Text = duration.TotalSeconds.ToString();

                SitesReturned.Text = "0";

                Cursor.Current = lastCursor;
                richTextBox_Reply.Text = eFLM.Message;

                try
                {
                    client.Close();
                }
                catch (Exception eService)
                {
                    richTextBox_Reply.Text += "\n\nThe FLM Service closed with the following error:\n   " + eService.Message;
                }

                return;
            }
            Cursor.Current = lastCursor;

            SitesReturned.Text = reply.SiteUriList.Count.ToString();

            string sXmlReply = GetDataTypeXmlString(typeof(SiteListType), reply);
            richTextBox_Reply.Text = sXmlReply;

            try
            {
                client.Close();
            }
            catch (Exception eService)
            {
                richTextBox_Reply.Text += "\n\nThe FLM Service closed with the following error:\n   " + eService.Message;
            }
        }

        private void query_sites_Click(object sender, EventArgs e)
        {
            query_sites_Uri();
        }

        private void all_sites_Uri()
        {
            FlmServiceClient client = null;
            try
            {
                client = new FlmServiceClient(comboBox_location.Text);
            }
            catch (Exception eFLM)
            {
                richTextBox_Reply.Text = eFLM.Message;

                try
                {
                    client.Close();
                }
                catch (Exception eService)
                {
                    richTextBox_Reply.Text += "\n\nThe FLM Service closed with the following error:\n   " + eService.Message;
                }

                return;
            }

            client.ClientCredentials.UserName.UserName = username.Text;
            client.ClientCredentials.UserName.Password = password.Text;

            richTextBox_Request.Text = "GetFacilityList()";

            Cursor lastCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            DateTime startTime = DateTime.Now;
            DateTime endTime = startTime;
            TimeSpan duration = endTime - startTime;

            ResponseTime.Clear();
            SitesReturned.Clear();
            richTextBox_Reply.Clear();

            SiteListType reply = null;
            try
            {
                reply = client.GetFacilityList();

                endTime = DateTime.Now;
                duration = endTime - startTime;
                ResponseTime.Text = duration.TotalSeconds.ToString();
            }
            catch (Exception eFLM)
            {
                endTime = DateTime.Now;
                duration = endTime - startTime;
                ResponseTime.Text = duration.TotalSeconds.ToString();

                SitesReturned.Text = "0";

                Cursor.Current = lastCursor;

                richTextBox_Reply.Text = eFLM.Message;

                try
                {
                    client.Close();
                }
                catch (Exception eService)
                {
                    richTextBox_Reply.Text += "\n\nThe FLM Service closed with the following error:\n   " + eService.Message;
                }

                return;
            }
            Cursor.Current = lastCursor;

            SitesReturned.Text = reply.SiteUriList.Count.ToString();

            string sXmlReply = GetDataTypeXmlString(typeof(SiteListType), reply);
            richTextBox_Reply.Text = sXmlReply;

            try
            {
                client.Close();
            }
            catch (Exception eService)
            {
                richTextBox_Reply.Text += "\n\nThe FLM Service closed with the following error:\n   " + eService.Message;
            }
        }

        private void all_sites_Click(object sender, EventArgs e)
        {
             all_sites_Uri();
        }

        public static string GetDataTypeXmlString(Type type, object val)
        {
            if (type == null) { throw new ArgumentNullException("type"); }
            if (val == null) { throw new ArgumentNullException("val"); }

            MemoryStream ms = new MemoryStream();
            string xml = null;
            try
            {
                DataContractSerializer dcs = new DataContractSerializer(type);

                using (XmlTextWriter xmlTextWriter = new XmlTextWriter(ms, System.Text.Encoding.Default))
                {
                    xmlTextWriter.Formatting = System.Xml.Formatting.Indented;
                    dcs.WriteObject(xmlTextWriter, val);
                    xmlTextWriter.Flush();
                    ms = (MemoryStream)xmlTextWriter.BaseStream;
                    ms.Flush();
                    xml = UTF8ByteArrayToString(ms.ToArray());
                }
            }
            finally
            {
                if (ms != null)
                {
                    ms.Close();
                    ms = null;
                }
            }
            return xml;
        }

        private static String UTF8ByteArrayToString(Byte[] characters)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            string constructedString = encoding.GetString(characters);
            return (constructedString);
        }

        private void buttonChangedSinceDateAndTime_Click(object sender, EventArgs e)
        {
            FlmServiceClient client = null;
            try
            {
                client = new FlmServiceClient(comboBox_location.Text);
            }
            catch (Exception eFLM)
            {
                richTextBox_Reply.Text = eFLM.Message;

                try
                {
                    client.Close();
                }
                catch (Exception eService)
                {
                    richTextBox_Reply.Text += "\n\nThe FLM Service closed with the following error:\n   " + eService.Message;
                }

                return;
            }

            client.ClientCredentials.UserName.UserName = username.Text;
            client.ClientCredentials.UserName.Password = password.Text;

            string request = dateTimePicker_ChangedSinceDateTime.Value.ToShortDateString() + " " + dateTimePicker_ChangedSinceDateTime.Value.Hour.ToString() + ":" + dateTimePicker_ChangedSinceDateTime.Value.Minute.ToString();
            richTextBox_Request.Text = "GetUpdatedFacilityListSinceDateTime(" + request + ")";

            Cursor lastCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            DateTime startTime = DateTime.Now;
            DateTime endTime = startTime;
            TimeSpan duration = endTime - startTime;

            ResponseTime.Clear();
            SitesReturned.Clear();
            richTextBox_Reply.Clear();

            SiteListType reply = null;
            try
            {
                reply = client.GetUpdatedFacilityListSinceDateTime(request);

                endTime = DateTime.Now;
                duration = endTime - startTime;
                ResponseTime.Text = duration.TotalSeconds.ToString();
            }
            catch (Exception eFLM)
            {
                endTime = DateTime.Now;
                duration = endTime - startTime;
                ResponseTime.Text = duration.TotalSeconds.ToString();

                SitesReturned.Text = "0";

                Cursor.Current = lastCursor;
                richTextBox_Reply.Text = eFLM.Message;

                try
                {
                    client.Close();
                }
                catch (Exception eService)
                {
                    richTextBox_Reply.Text += "\n\nThe FLM Service closed with the following error:\n   " + eService.Message;
                }

                return;
            }
            Cursor.Current = lastCursor;

            SitesReturned.Text = reply.SiteUriList.Count.ToString();

            string sXmlReply = GetDataTypeXmlString(typeof(SiteListType), reply);
            richTextBox_Reply.Text = sXmlReply;

            try
            {
                client.Close();
            }
            catch (Exception eService)
            {
                richTextBox_Reply.Text += "\n\nThe FLM Service closed with the following error:\n   " + eService.Message;
            }
        }

        private void buttonChangedSinceInterval_Click(object sender, EventArgs e)
        {
            FlmServiceClient client = null;
            try
            {
                client = new FlmServiceClient(comboBox_location.Text);
            }
            catch (Exception eFLM)
            {
                richTextBox_Reply.Text = eFLM.Message;

                try
                {
                    client.Close();
                }
                catch (Exception eService)
                {
                    richTextBox_Reply.Text += "\n\nThe FLM Service closed with the following error:\n   " + eService.Message;
                }

                return;
            }

            client.ClientCredentials.UserName.UserName = username.Text;
            client.ClientCredentials.UserName.Password = password.Text;

            string request = maskedTextBoxChangeInterval.Text;
            richTextBox_Request.Text = "GetUpdatedFacilityListInterval(" + request + ")";

            Cursor lastCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            DateTime startTime = DateTime.Now;
            DateTime endTime = startTime;
            TimeSpan duration = endTime - startTime;

            ResponseTime.Clear();
            SitesReturned.Clear();
            richTextBox_Reply.Clear();

            SiteListType reply = null;
            try
            {
                reply = client.GetUpdatedFacilityListInterval(request);

                endTime = DateTime.Now;
                duration = endTime - startTime;
                ResponseTime.Text = duration.TotalSeconds.ToString();
            }
            catch (Exception eFLM)
            {
                endTime = DateTime.Now;
                duration = endTime - startTime;
                ResponseTime.Text = duration.TotalSeconds.ToString();

                SitesReturned.Text = "0";

                Cursor.Current = lastCursor;
                richTextBox_Reply.Text = eFLM.Message;

                try
                {
                    client.Close();
                }
                catch (Exception eService)
                {
                    richTextBox_Reply.Text += "\n\nThe FLM Service closed with the following error:\n   " + eService.Message;
                }

                return;
            }
            Cursor.Current = lastCursor;

            SitesReturned.Text = reply.SiteUriList.Count.ToString();

            string sXmlReply = GetDataTypeXmlString(typeof(SiteListType), reply);
            richTextBox_Reply.Text = sXmlReply;

            try
            {
                client.Close();
            }
            catch (Exception eService)
            {
                richTextBox_Reply.Text += "\n\nThe FLM Service closed with the following error:\n   " + eService.Message;
            }

        }
    }
}
